from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware

from controller.ai_controller import router as ai_router
from controller.media_controller import router as media_router
from controller.image_controller import router as image_router
from controller.wx_controller import router as wx_router
from controller.auth_controller import AuthMiddleware

app = FastAPI(docs_url=None, redoc_url=None, title="FunGPT", description="chatbot")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 自定义认证中间件，排除微信回调接口
class CustomAuthMiddleware(AuthMiddleware):
    async def dispatch(self, request, call_next):
        # 微信回调接口不需要认证
        if request.url.path.startswith("/api/wx/"):
            return await call_next(request)
        return await super().dispatch(request, call_next)

# 添加自定义认证中间件
app.add_middleware(CustomAuthMiddleware)

# 注册路由
app.include_router(ai_router)
app.include_router(media_router)
app.include_router(image_router)
app.include_router(wx_router)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=8006, workers=1)